package com.guigu.controller;


import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.pojo.Carousel;
import com.guigu.pojo.Consumer;
import com.guigu.pojo.UserAddress;
import com.guigu.service.ConsumerService;
import com.guigu.service.UserAddressService;
import com.guigu.utils.FileUploadUtils;
import com.guigu.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前台用户表 前端控制器
 * </p>
 *
 * @author Mr.Zhang
 * @since 2025-03-12
 */
@CrossOrigin
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private UserAddressService userAddressService;
    //用户民密码登录
    @PostMapping("/login")
    public Consumer login(Consumer consumer) {
        // 根据用户名和密码查询用户
        consumer = consumerService.selectOneByLoginNameAndPassword(consumer.getLoginName(), consumer.getPassword());
        return consumer;
    }
    //手机号登录
    @GetMapping("/loginByPhone")
    public Object loginByPhone(String phone){
        return (Consumer) consumerService.loginByPhone(phone);
    }
    //手机号密码注册
    @PostMapping("/register")
    @ResponseBody
    public Consumer register(Consumer consumer){
        String phone = consumer.getPhone();
        Object o = consumerService.loginByPhone(phone);
        if (o != null){
            return null;
        }
        consumer.setNickName(consumer.getLoginName());
        consumer.setCreateDate(new Date());
        return consumerService.register(consumer);
    }
    //更新用户信息
    @PostMapping("/updateUser")
    @ResponseBody
    @Transactional
    public Consumer updateUser(@RequestParam("files") MultipartFile[] files, Consumer user, UserAddress  address, HttpServletRequest req) {
        // 创建用户对象并设置用户名和密码
        System.out.println("user:"+user);
        System.out.println("address:"+address);

        // 设置文件上传的基础路径，并根据日期生成子路径
        String basePathStr = "C:\\Users\\Mr.Zhang\\document\\upload";
        String subPath = FileUploadUtils.makeUploadDirectoryByDate();
        basePathStr += subPath; // 文件上传的地址

        // 检查基础路径是否存在，如果不存在则创建
        File basePath = new File(basePathStr);
        if (!basePath.exists()) {
            basePath.mkdirs();
        }

        try {
            // 遍历上传的文件数组，重命名文件并保存到指定路径
            for (MultipartFile f : files) {
                String newFileName = FileUploadUtils.rename(f.getOriginalFilename());
                f.transferTo(new File(basePath, newFileName));
                user.setAvatarImg(subPath + newFileName);// 设置用户头像路径
            }
        } catch (Exception e) {
            throw new RuntimeException(e); // 捕获并抛出异常
        }

        user.setUpdateDate(new Date());
        // 保存用户信息并返回结果
        boolean b = consumerService.updateById(user);
        if (b) {
            QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("consumer_id", user.getConsumerId());
            Map<String, Object> map = userAddressService.getMap(queryWrapper);
            boolean update = true;
            if (map != null){
                UserAddress userAddress = new UserAddress();
                userAddress.setIsDefault(0);
                update = userAddressService.update(queryWrapper);
            }else{
                map.forEach((k, v) -> {
                    System.out.println(k + ":" + v);
                });
            }
            if (update){
                address.setConsumerId(user.getConsumerId());
                address.setIsDefault(1);
                boolean save = userAddressService.save(address);
            }
        }else {
            return null;
        }
        return user;
    }

    //通过id获得用户信息
    @GetMapping("/getUserById")
    @ResponseBody
    public Consumer getUserById(Integer consumerId){
        Consumer user = consumerService.getById(consumerId);
        List<UserAddress> addressByConsumerId = userAddressService.getAddressByConsumerId(consumerId);
        user.setUserAddress(addressByConsumerId);
        return user;
    }

    @PostMapping("/updatePassword")
    @ResponseBody
    public Integer updatePassword(@RequestParam HashMap<String,Object> map){
        return consumerService.updatePassword(map);
    }

}

